#!/bin/bash

if [[ $# < 1 ]]; then
	echo "Inform the config name";
	exit;
fi

NAME=$1

if [[ $# < 2 ]]; then
	N=0;
else
	N=$2;
fi

if [ ! -e "$NAME-$N.sca" ]; then
	echo "Config $NAME-$N not found";
	exit;
fi

echo "Saving global stats in $NAME-$N.all.csv"

scavetool scalar -p "module(**.peer[*].app) AND (name("Startup") OR name("Rank"))" -O $NAME.all.file -F csv $NAME-$N.sca
tail -n+2 $NAME.all.file | awk -F, 'BEGIN {max=0; sum=0; sumq=0} {sum+=$5; sumq+=$5*$5; if ($5 > max) max=$5;} END {avg = sum/NR; std=sqrt( (sumq-NR*(avg**2))/NR ); print avg,std,max}' > $NAME-$N.all.csv

echo "Saving ranked stats in $NAME-$N.rank.csv"
scavetool scalar -p "module(**.peer[*].app) AND (name("Startup") OR name("Rank"))" -O $NAME.rank.file -F csv $NAME-$N.sca
tail -n+2 $NAME.rank.file | sort -g | awk -F, 'BEGIN {max=0;} {n[$4]++;sum[$4]+=$5; sumq[$4]+=$5*$5; if ($4 > max) max=$4;} END {for (var in sum)print var,sum[var],sumq[var],n[var];}' | sort -g | awk '{if ($4 > 1) print $1,$2/$4,sqrt( ($3/$4) - (($2/$4)**2) ); else print $1,$2/$4,0};' > $NAME-$N.rank.csv

echo "Saving packets stats in $NAME.packets.csv"
scavetool scalar -p "module(**.queue) AND name(\"packets received by queue\")" -O $NAME.packet.file -F csv $NAME-$N.sca
tail -n+2 $NAME.rank.file | sort -g | awk -F, 'BEGIN {sum=0;} {sum+=$4;} END {print sum;}' > $NAME-$N.packet.csv


echo "Cleaning temporary files"
rm *.file

echo "Saving plot in $NAME.eps"

MEAN=`awk '{print $2;}' $NAME-$N.all.csv`

gnuplot <<EOF

set terminal postscript eps enhanced defaultplex "Helvetica" 16
set output '$NAME-$N.eps'

set grid
set yrange [0:]
#set xrange [0:]
set xlabel "Rank"
set ylabel "Mean Time"

set style data histogram
set style histogram cluster gap 2
set style fill solid 1 border 2
#set xtics rotate by 45 scale 0
#unset key
set tmargin 1

a = 0
b = 0
c = 0
d = 0
e = 0
f = 0

FIT_MAXITER = 1000

f(x) = a*(x**5) + b*(x**4) + c*(x**3) + d*(x**2) + e*x + f

fit f(x) '$NAME-$N.rank.csv' using 1:2 via a,b,c,d,e,f


plot '$NAME-$N.rank.csv' using 1:2 with linespoints pt 2 lt 2 lw 2 title 'Ranked Mean',\
	$MEAN with lines lt 3 lw 1 title 'Global Mean',\
	a*(x**5) + b*(x**4) + c*(x**3) + d*(x**2) + e*x + f with lines lt 1 lw 1 title 'Polynomial Fit'
	

EOF


